import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'
const UserKey = 'Admin-User'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token, { expires: 7 })
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

export function getUser() {
  const user = Cookies.get(UserKey)
  return user ? JSON.parse(user) : null
}

export function setUser(user) {
  return Cookies.set(UserKey, JSON.stringify(user), { expires: 7 })
}

export function removeUser() {
  return Cookies.remove(UserKey)
}

// 权限检查
export function hasPermission(permission) {
  const user = getUser()
  if (!user || !user.permissions) return false
  return user.permissions.includes(permission)
}

// 角色检查
export function hasRole(role) {
  const user = getUser()
  if (!user || !user.role) return false
  
  // 处理不同的数据结构
  const userRole = user.role.name || user.role.roleName || user.role.code || user.role.roleCode
  return userRole === role || 
         (user.role.code && user.role.code === role) || 
         (user.role.roleCode && user.role.roleCode === role)
}
